#include "StdAfx.h"
#include "TaxiAgent.h"
#include <algorithm>

CTaxiAgent::CTaxiAgent(int id, CNode* node) 
    : CCarAgent(id, node, ETYPE_TAXI)
{
    m_fare = NULL;
    m_path = NULL;
    m_hasJob = false;
    m_onJob = false;
}

CTaxiAgent::~CTaxiAgent(void)
{
}

bool CTaxiAgent::Step(CEnv* env, int ms)
{
    bool onPath = __super::Step(env, ms);

    if (!onPath)
    {
        if (m_onJob)
        {
            // Job completed
            TRACE("Job complete: %d -> %d\n", m_fare->m_start->m_id, m_fare->m_end->m_id);
            CFarePtrVec* fares = env->GetFares();
            CFarePtrVecIter it = std::find(fares->begin(), fares->end(), m_fare);
            fares->erase(it);
            delete m_fare;
            m_fare = NULL;
            m_onJob = false;
            m_hasJob = false;
        }

        if (!m_hasJob)
        {
            // Get next job
            m_fare = env->GetClosestFare(m_node);
            if (m_fare == NULL)
            {
                return false;
            }

            m_hasJob = true;
            m_onJob = false;
            
            // Get path to start
            if (m_node != m_fare->m_start)
            {
                CPath* path = CPath::FindPath(m_node->m_id, 
                    m_fare->m_start->m_id, env->GetNodeMap()->m_vecPaths);
                SetPath( path );
            }
        }
        else
        {
            // Set path from start to end of job
            SetPath( CPath::FindPath(m_node->m_id,
                m_fare->m_end->m_id, env->GetNodeMap()->m_vecPaths) );
            m_onJob = true;
            m_fare->Start();
        }
    }

    return true;
}


